import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {Product, products} from '../products';
import {CarService} from "../car.service";

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
  // 定义product属性
  product: Product | undefined;

  /**
   *  constructor是ProductDetailsComponent类的构造器
   *  可进行任意配置...将需要的东西 丢到constructor中..就附加到类上了
   * 通过把 private route: ActivatedRoute
   * 添加为构造函数括号内的参数，
   * 来把 ActivatedRoute 注入到 constructor() 中
   * @param route
   */
  constructor(
    private route: ActivatedRoute,
    private carService: CarService
  ) {
  }

  /**
   * 在 ngOnInit() 方法中，
   * 从路由参数中提取 productId
   * 并在 products 数组中找到相应的产品。
   */
  ngOnInit(): void {
    // First get the product id from the current route.
    // 使用 route.snapshot访问路由参数
    const routeParams = this.route.snapshot.paramMap   //route(ActivatedRoute).snapshot其实就是 ActivatedRouteSnapshot类型  当前路由快照
    const productIdFromRoute = Number(routeParams.get('productId'))

    // Find the product that correspond with the id provided in route.
    this.product = products.find(product => product.id === productIdFromRoute)
  }

  /**
   * 以当前product作为参数
   *
   * 使用 CartService addToCart() 方法去添加产品到购物车中
   *
   * 显示一条你已经添加了一个产品到购物车到消息
   * @param product
   */
  addToCart(product: Product) {
    this.carService.addToCart(product)
    window.alert('Your product has been added to the cart!');
  }

  /* ... */
}
